package top.easydict.user.domain.innerservice.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.easydict.enums.DelStatusEnum;
import top.easydict.enums.UserStatusEnum;
import top.easydict.user.domain.dao.UserMapper;
import top.easydict.user.domain.dao.table.UserTableDO;
import top.easydict.user.domain.entity.UserDO;
import top.easydict.user.domain.innerservice.UserServices;
import top.easydict.user.online.dto.UserRequestDTO;
import top.easydict.util.extend.MD5Util;
import top.easydict.util.redis.RedisUtil;

import javax.annotation.Resource;
import java.io.File;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServicesImp implements UserServices {
    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public UserDO addUser(UserDO userDO) {
        UserTableDO userTableDO = new UserTableDO();
        userTableDO.setUserName(userDO.getUsername());
        userTableDO.setPassword(userDO.getPassword());
        int insert = userMapper.insert(userTableDO);
        if (insert == 1) {
            userDO.setMessge("添加用户成功!");
        } else {
            userDO.setMessge("添加用户失败!");
        }
        return userDO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map register(UserRequestDTO userRequestDTO) {
        //TODO 邀请人后续再做
        Map<String, String> map = new HashMap<>();
        //获取参数
        String username = userRequestDTO.getUsername();
        //密码MD5加密 (后续有需要可以加盐)
        String password = MD5Util.md5Hex(userRequestDTO.getPassword());
        String email = userRequestDTO.getEmail();
        String phone = userRequestDTO.getPhone();
        Timestamp createTime = new Timestamp(System.currentTimeMillis());
        //校验
        Map checkMap = checkRegisterInfo(username, email, phone);
        if ("0".equals(checkMap.get("success"))) {
            return checkMap;
        }
        UserTableDO userTableDO = new UserTableDO();
        userTableDO.setUserName(username);
        userTableDO.setPassword(password);
        userTableDO.setEmail(email);
        userTableDO.setPhone(phone);
        userTableDO.setCreateTime(createTime);
        //冻结
        userTableDO.setStatus(UserStatusEnum.FROZEN.getCode());
        userTableDO.setIsDelete(DelStatusEnum.NOTDEL.getCode());
        //插入数据库
        Integer insert = userMapper.insert(userTableDO);
        //发送邮件
        sendEmail(email, userTableDO.getUserId());

        if (insert == 1) {
            map.put("success", "1");
            map.put("msg", "添加用户成功");
        } else {
            map.put("success", "0");
            map.put("msg", "添加用户失败");
        }
        return map;
    }

    @Override
    public Map checkRegisterInfo(String username, String email, String phone) {
        Map<String, String> map = new HashMap<>();
        map.put("success", "1");
        map.put("msg", "信息校验成功");
        //校验用户名是否重复
        Integer countUsername = userMapper.selectCount(new QueryWrapper<UserTableDO>()
                .eq("user_name", username)
                .eq("status", UserStatusEnum.ACTIVE.getCode())
                .eq("is_delete", DelStatusEnum.NOTDEL.getCode()));
        if (countUsername > 0) {
            map.put("success", "0");
            map.put("msg", "用户名已存在");
            return map;
        }
        //校验邮箱是否重复
        Integer emailCount = userMapper.selectCount(new QueryWrapper<UserTableDO>()
                .eq("email", email)
                .eq("status", UserStatusEnum.ACTIVE.getCode())
                .eq("is_delete", DelStatusEnum.NOTDEL.getCode()));
        if (emailCount > 0) {
            map.put("success", "0");
            map.put("msg", "邮箱已存在");
            return map;
        }
        //校验手机号码
        Integer phoneCount = userMapper.selectCount(new QueryWrapper<UserTableDO>()
                .eq("phone", phone)
                .eq("status", UserStatusEnum.ACTIVE.getCode())
                .eq("is_delete", DelStatusEnum.NOTDEL.getCode()));
        if (phoneCount > 0) {
            map.put("success", "0");
            map.put("msg", "手机号已存在");
            return map;
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map checkRegisterCode(Long userId, String code) {
        Map<String, String> map = new HashMap<>();
        boolean hasKey = redisUtil.hasKey("registerUser:" + userId);
        if (hasKey) {
            String s = redisUtil.get("registerUser:" + userId).toString();
            if (StringUtils.isBlank(code)) {
                map.put("success", "0");
                map.put("msg", "请输入验证码");
            }
            if (s.equals(code)) {
                UserTableDO userTableDO = new UserTableDO();
                userTableDO.setUserId(userId);
                userTableDO.setStatus(UserStatusEnum.ACTIVE.getCode());
                userTableDO.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                userMapper.updateById(userTableDO);
                map.put("success", "1");
                map.put("msg", "验证码正确,注册成功");
            } else {
                map.put("success", "0");
                map.put("msg", "验证码错误");
            }
        } else {
            map.put("success", "0");
            map.put("msg", "验证码已过期");
        }
        return map;
    }

    private void sendEmail(String mail, Long userId) {
        String mailSubject = "注册验证码";
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(111, 36, 4, 2);
        String mailContent = captcha.getCode();
        //TODO 想往邮箱里面塞captchar的图片
//        String src = "<img  src=\"data:image/png;base64,"+ captcha.getImageBase64() + "\">";
//        MailUtil.sendHtml(userRequestDTO.getEmail(),mailSubject, src, new File("..\\xxxx\\xxxx.html"));
        String send = MailUtil.send(mail, mailSubject, mailContent, false);
        log.info("发送邮件信息: {}",send);
        //五分钟有效
        redisUtil.set("registerUser:" + userId, mailContent, 300);
    }
}
